package com.jone.phone.detail.db;



import java.util.HashMap;

import com.jone.phone.detail.model.DayStat;
import com.jone.phone.detail.model.MonthStat;
import com.jone.phone.detail.model.SmsDetail;
import com.jone.phone.detail.model.TeleDetail;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;



public class DataProvider extends ContentProvider {
	private static final String TAG = "DataProvider";
	private static final String DATABASE_NAME ="detail.db";
	private static final int DATABASE_VER =1;
	private static final String TABLE_NAME_SMS = "sms_detail";	
	private static final String TABLE_NAME_TELE = "tele_detail";	
	
	private static final String TABLE_MONTH_STAT = "month_stat";	
	private static final String TABLE_DAY_STAT = "day_stat";	
    
    
    private static HashMap<String, String> smsProjectionMap;
    
    private static HashMap<String, String> teleProjectionMap;
    
    private static HashMap<String, String> monthProjectionMap;
    
    private static HashMap<String, String> dayProjectionMap;

    private static final int SMS_DETAIL = 0;
    private static final int TELE_DETAIL = 1;
    private static final int MONTH_STAT = 2;
    private static final int DAY_STAT = 3;
    private static final int PERSON_COUNT = 4;
    

    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	
    private DatabaseHelper mOpenHelper;
    
    static {
        sUriMatcher.addURI("com.jone.phone.detail", "sms_detail", SMS_DETAIL);
        sUriMatcher.addURI("com.jone.phone.detail", "tele_detail", TELE_DETAIL);
        sUriMatcher.addURI("com.jone.phone.detail", "month_stat", MONTH_STAT);
        sUriMatcher.addURI("com.jone.phone.detail", "day_stat", DAY_STAT);
        sUriMatcher.addURI("com.jone.phone.detail", "person_count", PERSON_COUNT);

        smsProjectionMap = new HashMap<String, String>();
        smsProjectionMap.put(SmsDetail._ID, SmsDetail._ID);
        smsProjectionMap.put(SmsDetail.PERSON_ID, SmsDetail.PERSON_ID);
        smsProjectionMap.put(SmsDetail.PERSON_NUMBER, SmsDetail.PERSON_NUMBER);
        smsProjectionMap.put(SmsDetail.PERSON_NAME, SmsDetail.PERSON_NAME);
        smsProjectionMap.put(SmsDetail.TYPE, SmsDetail.TYPE);
        smsProjectionMap.put(SmsDetail.TIME, SmsDetail.TIME);
        smsProjectionMap.put(SmsDetail.SUBJECT, SmsDetail.SUBJECT);
        smsProjectionMap.put(SmsDetail.BODY, SmsDetail.BODY);
        
        teleProjectionMap = new HashMap<String, String>();
        teleProjectionMap.put(TeleDetail._ID, TeleDetail._ID);
        teleProjectionMap.put(TeleDetail.PERSON_ID, TeleDetail.PERSON_ID);
        teleProjectionMap.put(TeleDetail.PERSON_NUMBER, TeleDetail.PERSON_NUMBER);
        teleProjectionMap.put(TeleDetail.PERSON_NAME, TeleDetail.PERSON_NAME);
        teleProjectionMap.put(TeleDetail.TYPE, TeleDetail.TYPE);
        teleProjectionMap.put(TeleDetail.TIME, TeleDetail.TIME);
        teleProjectionMap.put(TeleDetail.DURATION, TeleDetail.DURATION);
        
        monthProjectionMap = new HashMap<String, String>();
        monthProjectionMap.put(MonthStat._ID, MonthStat._ID);
        monthProjectionMap.put(MonthStat.MONTH, MonthStat.MONTH);
        monthProjectionMap.put(MonthStat.KEY, MonthStat.KEY);
        monthProjectionMap.put(MonthStat.NUM, MonthStat.NUM);
        
        dayProjectionMap = new HashMap<String, String>();
        dayProjectionMap.put(DayStat._ID, DayStat._ID);
        dayProjectionMap.put(DayStat.DAY, DayStat.DAY);
        dayProjectionMap.put(DayStat.KEY, DayStat.KEY);
        dayProjectionMap.put(DayStat.NUM, DayStat.NUM);        
        
         
    }	
	
   @Override
    public boolean onCreate() 
   	{
	   Log.i("DEMO","DataProvider>>>onCreate ");
	        mOpenHelper = new DatabaseHelper(getContext());
	        mOpenHelper.getWritableDatabase();
	        return true;
   	}


	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		  SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	       int count = 0;
	        switch (sUriMatcher.match(uri)) {
	        case SMS_DETAIL:
	            count = db.delete(TABLE_NAME_SMS, where, whereArgs);
	            break;
	        case TELE_DETAIL:
	        	count = db.delete(TABLE_NAME_TELE, where, whereArgs);
	        	break;	        
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        getContext().getContentResolver().notifyChange(uri, null);
	        return count;
	}

	@Override
	public String getType(Uri uri) {
		Log.i("DEMO","DataProvider>>> getType");
		  switch (sUriMatcher.match(uri)) {
	        case SMS_DETAIL:
	            return SmsDetail.CONTENT_TYPE;
	        case TELE_DETAIL:
	        	return TeleDetail.CONTENT_TYPE;	 
	        case PERSON_COUNT:
	        	return TeleDetail.CONTENT_TYPE;
	        case MONTH_STAT:
	        	return MonthStat.CONTENT_TYPE;
	        case DAY_STAT:
	        	return DayStat.CONTENT_TYPE;
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {		
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		long rowId = 0; 
		Uri retUri = null;
		
		switch (sUriMatcher.match(uri)) {
	
		case SMS_DETAIL:
			rowId = db.insert(TABLE_NAME_SMS, null, values);
			retUri = ContentUris.withAppendedId(SmsDetail.URI_SMS_DETAIL, rowId);
			break;	
		case TELE_DETAIL:
			rowId = db.insert(TABLE_NAME_TELE, null, values);
			retUri = ContentUris.withAppendedId(TeleDetail.URI_TELE_DETAIL, rowId);
			break;	
		case MONTH_STAT:
			rowId = db.insert(TABLE_MONTH_STAT, null, values);
			retUri = ContentUris.withAppendedId(MonthStat.URI_MONTH_STAT, rowId);
			break;	
		case DAY_STAT:
			rowId = db.insert(TABLE_DAY_STAT, null, values);
			retUri = ContentUris.withAppendedId(DayStat.URI_DAY_STAT, rowId);
			break;	
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		
		return retUri;
	}



	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		
			Log.i("DEMO", "DataProvider.query....");
		
		   SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		   String groupBy = null;
		   String having = null;

	        switch (sUriMatcher.match(uri)) {
	        case SMS_DETAIL:
	        	 qb.setTables(TABLE_NAME_SMS);
		         qb.setProjectionMap(smsProjectionMap);
	        	break;	
	        case TELE_DETAIL:
	        	 qb.setTables(TABLE_NAME_TELE);
		         qb.setProjectionMap(teleProjectionMap);
	        	break;	 
	        case MONTH_STAT:
	        	 qb.setTables(TABLE_MONTH_STAT);
		         qb.setProjectionMap(monthProjectionMap);
	        	break;	 
	        case DAY_STAT:
	        	 qb.setTables(TABLE_DAY_STAT);
		         qb.setProjectionMap(dayProjectionMap);
	        	break;	
	        case PERSON_COUNT:
	        	qb.setTables(TABLE_NAME_TELE);
	        	groupBy = "person_number";	        	
	        	break;
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        // If no sort order is specified use the default
	        String orderBy;
	        if (TextUtils.isEmpty(sortOrder)) {
	            orderBy = " _id desc";
	        } else {
	            orderBy = sortOrder;
	        }

	        // Get the database and run the query
	        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
	        Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, having, orderBy);

	        // Tell the cursor what uri to watch, so it knows when its source data changes
	        c.setNotificationUri(getContext().getContentResolver(), uri);
	        return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {
		 
		  SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	        int count;
	        switch (sUriMatcher.match(uri)) {
	        case SMS_DETAIL:
	            count = db.update(TABLE_NAME_SMS, values, where, whereArgs);
	            break;	
	        case TELE_DETAIL:
	            count = db.update(TABLE_NAME_TELE, values, where, whereArgs);
	            break;	  
	        case MONTH_STAT:
	        	String month = values.getAsString(MonthStat.MONTH);
	        	String key = values.getAsString(MonthStat.KEY);
	        	int mnum = values.getAsInteger(MonthStat.NUM);
	        	db.execSQL("update month_stat set s_num = s_num+" + mnum +" where s_month = '"+month+"' and s_key = '"+key+"'");
	        	count = 1;
	        	break;
	        case DAY_STAT:
	        	String day = values.getAsString(DayStat.DAY);
	        	String dkey = values.getAsString(DayStat.KEY);
	        	int dnum = values.getAsInteger(DayStat.NUM);
	        	db.execSQL("update day_stat set s_num = s_num+"+dnum+" where s_day = '"+day+"' and s_key = '"+dkey+"'");
	        	count = 1;
	        	break;
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        getContext().getContentResolver().notifyChange(uri, null);
	        return count;
	}	
	
	 
	 
	 private static class DatabaseHelper extends SQLiteOpenHelper{	
			
			public DatabaseHelper(Context context) {			
				super(context, DATABASE_NAME, null, DATABASE_VER);
				Log.i(TAG,"DatabaseHelper DatabaseHelper");
			}

			@Override
			public void onCreate(SQLiteDatabase db) {			
				Log.v(TAG, "db onCreate begin------------------");
				
				//日统计
				StringBuffer sql = new StringBuffer();				
				sql.append("CREATE TABLE if not exists day_stat(");
				sql.append("_id INTEGER PRIMARY KEY AUTOINCREMENT,");
				sql.append("s_day varchar(8),");
				sql.append("s_key varchar(30),");
				sql.append("s_num INTEGER)");
				db.execSQL(sql.toString());	
				
				//月统计
				sql = new StringBuffer();				
				sql.append("CREATE TABLE if not exists month_stat(");
				sql.append("_id INTEGER PRIMARY KEY AUTOINCREMENT,");
				sql.append("s_month varchar(6),");
				sql.append("s_key varchar(30),");
				sql.append("s_num INTEGER)");
				db.execSQL(sql.toString());		
				
				//短信记录
				sql = new StringBuffer();				
				sql.append("CREATE TABLE if not exists sms_detail(");
				sql.append("_id INTEGER PRIMARY KEY AUTOINCREMENT,");
				sql.append("person_id INTEGER,");
				sql.append("person_number varchar(30),");
				sql.append("person_name varchar(30),");
				sql.append("type INTEGER,");
				sql.append("time varchar(14),");
				sql.append("subject text,");
				sql.append("body text)");
				db.execSQL(sql.toString());		
				
				//电话记录
				sql = new StringBuffer();				
				sql.append("CREATE TABLE if not exists tele_detail(");
				sql.append("_id INTEGER PRIMARY KEY AUTOINCREMENT,");
				sql.append("person_id INTEGER,");
				sql.append("person_number varchar(30),");
				sql.append("person_name varchar(30),");
				sql.append("type INTEGER,");
				sql.append("time varchar(14),");
				sql.append("duration INTEGER)");
				db.execSQL(sql.toString());					
				
				 // ---------------------------------- 插入一些默认数据
//			    String hsql = "INSERT INTO month_stat (s_month, s_key, s_num) VALUES ";		
//			    db.execSQL(hsql + "('201003','call_in',500);");
//			    db.execSQL(hsql + "('201004','call_in',600);");
//			    db.execSQL(hsql + "('201005','call_in',400);");
//			    db.execSQL(hsql + "('201003','call_out',800);");
//			    db.execSQL(hsql + "('201004','call_out',800);");
//			    db.execSQL(hsql + "('201005','call_out',600);");
//			    
//			    hsql = "INSERT INTO day_stat (s_day, s_key, s_num) VALUES ";		
//			    db.execSQL(hsql + "('20100501','call_out',50);");
//			    db.execSQL(hsql + "('20100502','call_out',60);");
//			    db.execSQL(hsql + "('20100510','call_out',40);");
//			    db.execSQL(hsql + "('20100513','call_out',80);");
//			    db.execSQL(hsql + "('20100514','call_out',20);");
//			    db.execSQL(hsql + "('20100515','call_out',90);");
//			    
//			    hsql = "INSERT INTO tele_detail (person_number, person_name, type,time,duration) VALUES ";		
//			    db.execSQL(hsql + "('13714542350','',1,'20100501',5000);");
//			    db.execSQL(hsql + "('13714542350','',2,'20100502',3000);");
//			    db.execSQL(hsql + "('13800138000','',1,'20100504',5000);");
//			    db.execSQL(hsql + "('13800138000','',2,'20100505',6000);");
//			    db.execSQL(hsql + "('13888888888','',1,'20100501',3000);");
//			    db.execSQL(hsql + "('13428723113','',2,'20100501',10000);");
//			    db.execSQL(hsql + "('5556','',1,'20100501',6000);");
//			    db.execSQL(hsql + "('5554','',1,'20100501',3000);");
			    			    
				Log.v(TAG, "DB init success!------------------------");
			}

			@Override
			public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
				
				  
			}
			
		}

}
